package com.archerdu.apply.controller.admin;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.archerdu.apply.model.Role;
import com.archerdu.apply.model.User;
import com.archerdu.apply.service.RoleManager;
import com.archerdu.apply.service.UserManager;
import com.archerdu.base.controller.BaseController;
import com.archerdu.base.dao.IPage;
import com.archerdu.commons.constant.DataConstant;
import com.archerdu.commons.util.ServletUtil;

/**
 * 
 * @projectName: springDemo
 * @package: com.archerdu.apply.controller.admin
 * @className: UserController
 * @description: 用户管理
 * @author: archer du
 * @createDate: 2013-8-9 下午5:00:10
 * @updateUser: dxf
 * @updateDate: 2013-8-9 下午5:00:10
 * @updateRemark: 新建
 * @version: 0.0.1
 */
@Controller
@Scope("prototype")
@RequestMapping("/admin/user")
public class UserController extends BaseController {

    private static final long serialVersionUID = -6777950424131138768L;

    private UserManager       userManager;

    private RoleManager       roleManager;

    private User              user;

    @RequestMapping(value = "/add")
    public ModelAndView add(HttpServletRequest requ, UserController uc) {
        ModelAndView mav = new ModelAndView();
        user = uc.getUser();

        if ("post".equalsIgnoreCase(requ.getMethod())) {
            try {
                user.setFlag(DataConstant.USER_FLAG_SYS);
                user.setRegIp(ServletUtil.getClientIpAddr(requ));
                user.setRegtime(getSqlDate());
                user.setUseFlag(DataConstant.COMMON_USE_FLAG_YES);
                userManager.add(user);
                addMessage(DataConstant.COMMON_ADD_SUCCESS);
            } catch (Exception e) {
                addMessage(DataConstant.COMMON_ADD_FAILED);
                logger.error(e.getMessage(), e);
            }
        }
        mav.addObject(getMessage());
        mav.setViewName("admin/user/add");
        return mav;
    }

    /**
     * 用户编辑
     * 
     * @param requ
     * @param uc
     * @return
     */
    @RequestMapping(value = "/edit")
    public ModelAndView edit(HttpServletRequest requ, UserController uc) {
        logger.debug("uc.getUser() is " + uc.getUser());
        user = uc.getUser();
        ModelAndView mav = new ModelAndView();
        if ("get".equalsIgnoreCase(requ.getMethod())) {
            if (!StringUtils.isEmpty(user.getId())) {
                user = userManager.get(user.getId());
                mav.addObject(user);
            }
        }

        mav.setViewName("admin/user/edit");
        return mav;
    }

    /**
     * 删除用户
     * 
     * @param requ
     * @param uc
     * @param pageNo
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/remove")
    public ModelAndView remove(HttpServletRequest requ, UserController uc, Integer pageNo, Integer pageSize) {
        user = uc.getUser();
        if (null != user && null != user.getId()) {
            user = userManager.get(user.getId());
            user.setUseFlag(DataConstant.COMMON_USE_FLAG_NO);
            try {
                userManager.modify(user);
                addMessage(DataConstant.COMMON_DEL_SUCCESS);
            } catch (Exception e) {
                addMessage(DataConstant.COMMON_DEL_FAILED);
                logger.error(e.getMessage(), e);
            }
        }

        ModelAndView mav = page(requ, uc, pageNo, pageSize);
        mav.addObject(getMessage());
        return mav;
    }

    /**
     * 用户分页查询
     * 
     * @param requ
     * @param uc
     * @param pageNo
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/page")
    public ModelAndView page(HttpServletRequest requ, UserController uc, Integer pageNo, Integer pageSize) {

        if (null == uc.getUser()) {
            user = new User();
        } else {
            user = uc.getUser();
        }
        user.setUseFlag(DataConstant.COMMON_USE_FLAG_YES);
        if (null == pageNo || null == pageSize) {
            pageNo = 1;
            pageSize = 20;
        }
        logger.debug("userManager is " + userManager);
        IPage<User> page = userManager.pageSearch(user, pageNo, pageSize);

        ModelAndView mav = new ModelAndView();
        mav.addObject(page).setViewName("admin/user/page");
        return mav;
    }

    @RequestMapping("/role")
    public ModelAndView role(HttpServletRequest request, UserController uc, Integer[] roleIds) {

        user = uc.getUser();
        ModelAndView mav = new ModelAndView();
        List<Role> roleList = new ArrayList<Role>();

        logger.info("begin to add roles");
        if ("post".equalsIgnoreCase(request.getMethod()) && null != user && null != user.getId()) {
            user = userManager.get(user.getId());

            Set<Role> roles = new HashSet<Role>();
            if (null != roleIds) {
                for (Integer i : roleIds) {
                    roles.add(roleManager.get(i));
                }
            }
            user.setRoles(roles);
            logger.info("begin to add roles");
            try {
                userManager.modifyByMerge(user);
                this.addMessage(DataConstant.COMMON_ADD_SUCCESS);
                logger.info("success to add use's roles");

            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                this.addMessage(DataConstant.COMMON_ADD_FAILED);
                logger.info("failed to add use's roles");
            }
        }

        // 获取所有关联角色
        if (null != user && null != user.getId()) {
            user = userManager.get(user.getId());
            roleList = roleManager.getAll();
            for (Role ro : roleList) {
                for (Role ro1 : user.getRoles()) {
                    if (ro.getId().equals(ro1.getId())) {
                        ro.setChecked(DataConstant.COMMON_HTML_CHECKED);
                        // struts2标签属性
                        // ro.setChecked("true");
                    }
                }
            }
            mav.addObject("roleList", roleList);
        }
        mav.addObject("user", user);
        mav.addObject(getMessage());
        return mav;
    }

    public void setUserManager(UserManager userManager) {
        this.userManager = userManager;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public RoleManager getRoleManager() {
        return roleManager;
    }

    public void setRoleManager(RoleManager roleManager) {
        this.roleManager = roleManager;
    }

    public UserManager getUserManager() {
        return userManager;
    }
}
